#!/bin/python
#-*- coding:utf-8 -*-
# Filename:    main.py
# Revision:    1.0
# Date:        2012-06-14
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
import sys
import os
import tornado.ioloop
import tornado.locale
import tornado.web
from dbmodel import *
from interface import *

class MyRequestHandler(tornado.web.RequestHandler):
    def check_xsrf_cookie(self):
        pass

def now_time():
    from time import strftime
    return strftime('%Y-%m-%d %H:%M:%S')

 
class GetProjectDeployHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _get_project_name = self.get_argument('s')
        _get_project_package = get_project_package_name('%s' % _get_project_name)
        _get_project_info = odb_project_info(_get_project_name)
        _get_wait_time = '%s' % _get_project_info['wait_time']
        _get_thread_num = '%s' % _get_project_info['thread_num']
        self.render("templates/getprojectdeploy.html", props = _get_project_package, \
                                                       project_info = _get_project_info, \
                                                       wt = _get_wait_time, tn = _get_thread_num)

class PlaybackLogHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _get_user_manage_project = if_get_user_project(_get_user)
        _get_log_name = self.get_argument("log")
        _html_context = []
        try:
            _log_file = open("tmplog/%s.log" % _get_log_name, "rb").readlines()
            for l in _log_file:
                _html_context.append(r'%s' % l)
        except:
            _html_context.append("not find log file")
        self.render("templates/mycontext.html", domain=_domain, \
                                                title=_title, \
                                                username = _get_user, \
                                                items=_get_user_left_menu, \
                                                error_context=_html_context)
        
class GetDeployStatusHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _get_status_log = self.get_argument('r')
        file=open("tmplog/%s.log"%_get_status_log, "rb").readlines()
        _deploy_log_context=""
        for i in file:
            _deploy_log_context+=i
        self.write(_deploy_log_context)


class GetProjectPackageHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user = self.get_secure_cookie("user").split(",")[0]
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _get_user_manage_project = if_get_user_project(_get_user)
        _get_project_package_name = self.get_argument("package")
        if os.path.isfile("static/temp/%s.zip" % _get_project_package_name):
            _package_name = '%s' % (_get_project_package_name)
        else:
            from random import randint    
            _ran_path_name = randint(10000, 99999)
            try:
                os.system("/bin/cp -r project/%s %s" % (_get_project_package_name, \
                                                        _ran_path_name)) 
                os.system("cd %s; /usr/bin/zip -r %s.zip *" %(_ran_path_name,\
                                                              _get_project_package_name)) 
            except:
                os.system("/usr/bin/zip %s.zip %s/Null" %(_get_project_package_name, _get_path))
            os.system("/bin/mv %s/%s.zip static/temp/%s.zip" % (_ran_path_name, \
                                                                _get_project_package_name, \
                                                                _get_project_package_name))
            os.system("/bin/rm -rf %s" % _ran_path_name)
            _now_root_path = os.getcwd()
            os.system("python %s/bin/timerdel.py -z %s/static/temp/%s.zip -w 300 &" % (_now_root_path, \
                                                                                       _now_root_path, \
                                                                                    _get_project_package_name))
            _package_name = _get_project_package_name
        self.render("templates/download.html", domain=_domain, \
                                               title=_title, \
                                               username = _get_user, \
                                               items=_get_user_left_menu,\
                                               packagename = "%s.zip" % _package_name)


class DeployHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _get_user_manage_project = if_get_user_project(_get_user)
        self.render("templates/deploy.html", domain=_domain, title=_title, \
                                             username = _get_user, \
                                             items=_get_user_left_menu, pros=_get_user_manage_project)
    def post(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _get_user_manage_project = if_get_user_project(_get_user)
        _get_project_name = self.get_argument('s')
        _get_project_id = if_get_project_id(_get_project_name)
        if u"%s" % _get_project_name == u"选择项目":
            self.write(u"别瞎操作")
            return
        _lock_status = odb_upload_deploy_lock(_get_project_name)
        if int(_lock_status['deploy_lock']) == 1:
            self.render("templates/mycontext.html", domain=_domain, \
                         title=_title, username = _get_user, \
                         items=_get_user_left_menu, \
                         error_context=["部署操作被锁。", \
                                        "稍后再试或与管理员联系。"])
            return
        try:
            _do = self.get_argument('do')
        except:
            self.render("templates/mycontext.html", domain=_domain, \
                        title=_title, username = _get_user, \
                        items=_get_user_left_menu, \
                        error_context=["部署或回退参数错误"])
        try:
            _reboot = self.get_argument('reboot')
        except:
            _reboot = 'off'
        try:
            _redo = self.get_argument('redo')
        except:
            _redo = 'off'
        try:
            _deploy_type = self.get_argument('deploy_type')
        except:
            self.render("templates/mycontext.html", domain=_domain, \
                        title=_title, username = _get_user, \
                        items=_get_user_left_menu, \
                        error_context=["部署方式参数错误"])
        try:
            _get_local_project = self.get_argument('RadioGroup1')
        except:
            self.render("templates/mycontext.html", domain=_domain, \
                        title=_title, username = _get_user, \
                        items=_get_user_left_menu, \
                        error_context=['没有选择要部署的版本'])
        from time import strftime
        _tmp_time = strftime('%Y%m%d%H%M%S')
        idb_deploy_lock(_get_project_name, _tmp_time)
        log_file = open("tmplog/%s.log" % _get_local_project, "ab")
        log_file.write('%s Use %s on %s project %s service do %s\n' % \
                                                              (now_time(), _get_user, \
                                                               _get_project_name, \
                                                               _get_local_project, \
                                                               _do))
        log_file.close()
        _now_root_path = os.getcwd()
        if _do == 'deploy' or _do == 'rollback':
            os.system("python %s/bin/backdeployment.py -p %s \
                                                       -d %s \
                                                       -r %s \
                                                       -a %s \
                                                       -t %s \
                                                       -s %s &" % \
                                                          (_now_root_path, \
                                                           _get_project_id, \
                                                           _do, _reboot, \
                                                           _redo, _deploy_type, \
                                                           _get_local_project))
          
        else:
            self.render("templates/mycontext.html", domain=_domain, \
                title=_title, items=_get_user_left_menu, \
                error_context=['部署方式错误'])
        self.render("templates/runstatus.html", domain=_domain, title=_title, \
                                                username = _get_user, \
                                                items=_get_user_left_menu, \
                                                log_file=_get_local_project, \
                                                loginterface='get_deploy_status')
